<?php

namespace App\Services;

use Carbon\Carbon;
use Dflydev\ApacheMimeTypes\PhpRepository;
use Illuminate\Support\Facades\Storage;

class UploadsManager
{
    protected $disk;
    protected $mimeDetect;

    public function __construct(PhpRepository $mimeDetect)
    {
        # code...
        $this->disk =  Storage::disk(config('blog.uploads.storage'));
        $this->mimeDetect = $mimeDetect;
    }

    /**
     * 返回文件夹内文件和目录
     * @param [type] $folder
     * @return array of [
     * 'folder' => '当前文件夹地址',
     * 'folderName' => '当前文件夹名字',
     * 'breadCrumbs'=> '文件夹目录面包屑',
     * 'folders' => '子目录数组[$path => $foldername]'
     * 'files' => '文件夹内的文件详情
     * ]
     */
    public function folderInfo($folder)
    {
        # code...
        $folder = $this->cleanFolder($folder);

        $breadcrumbs = $this->breadcrumbs($folder);
        $slice = array_slice($breadcrumbs, -1);
        $folderName = current($slice);
        $breadcrumbs = array_slice($breadcrumbs, 0, -1);

        $subfolders = [];
        foreach (array_unique($this->disk->directories($folder)) as $subfolder) {
            $subfolders["/$subfolder"] = basename($subfolder);
        }

        $files = [];
        foreach ($this->disk->files($folder) as $path) {
            $files[] = $this->fileDetails($path);
        }

        return compact(
            'folder',
            'folderName',
            'breadcrumbs',
            'subfolders',
            'files'
        );
    }

    protected function cleanFolder($folder)
    {
        return '/' . trim(str_replace('..', '', $folder), '/');
    }

    /**
     * 返回当前目录路径
     * @param [type] $folder
     * @return void
     */
    protected function breadcrumbs($folder)
    {
        $folder = trim($folder,'/');
        $crumbs = ['/'=>'root'];
        
        if(empty($folder)){
            return $crumbs;
        }

        $folders = explode('/',$folder);
        $build = '';
        foreach ($folders as $folder) {
            $build .='/'.$folder;
            $crumbs[$build] =$folder;
        }

        return $crumbs;
    }

    protected function fileDetails($path)
    {
        $path = '/' . ltrim($path, '/');

        return [
            'name' => basename($path),
            'fullPath' => $path,
            'webPath' => $this->fileWebpath($path),
            'mimeType' => $this->fileMimeType($path),
            'size' => $this->fileSize($path),
            'modified' => $this->fileModified($path),
        ];
    }

    /**
     * 返回文件完整的web路径
     * @param [type] $path
     * @return void
     */
    public function fileWebpath($path)
    {
        $path = rtrim(config('blog.uploads.webpath'),'/').'/'.ltrim($path,'/');
        return url($path);
    }

    /**
     * 返回文件MIME类型
     * @param [type] $path
     * @return void
     */
    public function fileMimeType($path)
    {
        return $this->mimeDetect->findType(
            pathinfo($path, PATHINFO_EXTENSION)
        );
    }

    /**
     * 返回文件大小
     * @param [type] $path
     * @return void
     */
    public function fileSize($path)
    {
        return $this->disk->size($path);
    }

    /**
     * 返回最后修改时间
     * @param [type] $path
     * @return void
     */
    public function fileModified($path)
    {
        return Carbon::createFromTimestamp(
            $this->disk->lastModified($path)
        );
    }
    
    /**
     * 创建新目录
     * @param [type] $folder
     * @return void
     */
    public function createDirectory($folder)
    {
        $folder = $this->cleanFolder($folder);

        if ($this->disk->exists($folder)) {
            return "Folder '$folder' already exists";
        }

        return $this->disk->makeDirectory($folder);
    }
    
    /**
     * 删除目录
     * @param [type] $folder
     * @return void
     */
    public function deleteDirectory($folder)
    {
        $folder = $this->cleanFolder($folder);

        $filesFolders = array_merge($this->disk->directories($folder),$this->disk->files($folder));
        if (! empty($filesFolders)) {
            return "删除文件夹必须为空";
        }

        return $this->disk->deleteDirectory($folder);
    }

    /**
     * 删除文件
     * @param [type] $path
     * @return void
     */
    public function deleteFile($path)
    {
        $path = $this->cleanFolder($path);

        if (! $this->disk->exists($path)) {
            return "文件不存在";
        }
        return $this->disk->delete($path);
    }
    
    public function saveFile($path, $content)
    {
        $path = $this->cleanFolder($path);

        if ($this->disk->exists($path)) {
            return '文件不存在';
        }

        return $this->disk->put($path, $content);
    }
}
